package phantm.cfg

import Trees.Statement

class ControlFlowGraph extends LabeledDirectedGraphImp[Statement] {
  val entry: Vertex = newVertex
  val exit: Vertex = newVertex
  entry.name = "entry"
  exit.name = "exit"
  override def toString = "[>" + entry + super.toString + exit + "<]"

  def joinGraphsWithoutEntryAndExit(anotherGraph: ControlFlowGraph): Unit = {
    for (anEdge <- anotherGraph.E) {
      if (anEdge.v1 != anotherGraph.entry && anEdge.v2 != anotherGraph.exit) { this += (anEdge.v1, anEdge.lab, anEdge.v2) }
    }
  }

  def copyCFG: (ControlFlowGraph, Map[Vertex, Vertex]) = {
    val cfg = new ControlFlowGraph
    var vertexMap: Map[Vertex, Vertex] = Map()
    for (aVertex <- this.V) {
      if (aVertex == entry) vertexMap += (entry -> cfg.entry)
      else if (aVertex == exit) vertexMap += (exit -> cfg.exit)
      else vertexMap += (aVertex -> newVertex)
    }
    for (anEdge <- this.E) {
      cfg += (vertexMap(anEdge.v1), anEdge.lab, vertexMap(anEdge.v2))
    }
    Pair(cfg, vertexMap)
  }
}

